package com.example.demo1.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.SecretKey;

import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;

import java.nio.charset.StandardCharsets;

@Component
public class JWTUtil {
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
    private static final String KEY = "JEIe8hjVd3tTyS8X5ai9lA08FGd31FFCSNsjM7hygI6adb6ToeVjg3Dm/uRIVGgW9yUCxkkRN5J6fBBO9qjd3w==";

    public static String createToken(Integer userId) {
        Map<String, Object> header = new HashMap<String, Object>();
        header.put("copyRight", "TOPRS");
        SecretKey key = Keys.hmacShaKeyFor(KEY.getBytes(StandardCharsets.UTF_8));
        String token = Jwts.builder().setHeader(header).setId(userId.toString()).setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME)).signWith(key).compact();
        return token;
    }

    public static Claims getJwsClaims(String tokenString) {
        SecretKey key = Keys.hmacShaKeyFor(KEY.getBytes(StandardCharsets.UTF_8));
        Claims jwsClaims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(tokenString).getBody();
        return jwsClaims;
    }

    // Tool 用于将一个 秘钥转换为字符串 然后save
    public static void getKEY() {
        SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS512);
        String secretString = Encoders.BASE64.encode(key.getEncoded());
        System.out.println(secretString);

    }

    public static void main(String[] args) {
        // getId();
        System.out.println(createToken(1));
    }

}
